package com.example.flutter_study

import android.app.Service
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MainActivity : FlutterActivity() {
    val CHANNEL = "com.example.flutter.study"
    private val TAG = "MainActivity"
    private var bind: TimeService.MyBind? = null;
    private var result: MethodChannel.Result? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
    }

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
            this.result = result
            when (call.method) {
                "getAndroidData" -> {
                    Log.e(TAG, "configureFlutterEngine: " + call.method)
                    Log.e(TAG, "configureFlutterEngine: " + call.arguments)
                    result.success("调用成功，这是回调信息:method:" + call.method + ",args:" + call.arguments)
                }
                "getService" -> {
                    var intent = Intent(this, TimeService::class.java)
                    startService(intent)
                }
                "closeTimer"->{
                    stopService(Intent(this,TimeService::class.java))
                }
            }

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(count: String) {
        val messenger = flutterEngine?.dartExecutor?.binaryMessenger

        // 新建一个 Channel 对象
        val channel = MethodChannel(messenger, CHANNEL)
        var map = HashMap<String, String>()
        map.put("count", count)
        channel.invokeMethod("sendCount", map)
    }


}
